/**
 * Created by 3fuyu on 2016/11/24.
 *
 *
 * 功能说明：
 *
 * 鼠标点住左划，右划切换
 * 上划，下滑退出
 * 点击放大（如果可以放大）后可手型移动，再次点击缩小
 * 支持全屏浏览（如果需要）
 * 支持分享（如果需要）
 * 支持手机端（如果需要）
 *
 * 调用方法：
 *
 * 引入该js后调用showPhotoWall(photoWalls, index)即可
 *
 * 参数说明：
 *
 * photoWalls imgs array
 * index img index
 *
 * photoWalls = [{
 *     src: img src
 *     el: img's parent dom or higher
 * }]
 *
 */

define(['photoswipemin', 'photoswipeuimin'], function (PhotoSwipe, PhotoSwipeUI_Default) {
    "use strict";

    var photoSwipe = function () {
        this.init();
    };
    var photoSwipeInstance;

    photoSwipe.prototype = {
        init: function () {
            this.render();
        },
        render: function () {
            this.psDom = '<div class="pswp my-gallery" tabindex="-1" role="dialog" aria-hidden="true"><div class="pswp__bg"></div><div class="pswp__scroll-wrap"><div class="pswp__container"><div class="pswp__item"></div><div class="pswp__item"></div><div class="pswp__item"></div></div><div class="pswp__ui pswp__ui--hidden"><div class="pswp__top-bar"><div class="pswp__counter"></div><button class="pswp__button pswp__button--close" title="Close (Esc)"></button><button class="pswp__button pswp__button--zoom" title="Zoom in/out"></button><div class="pswp__preloader"><div class="pswp__preloader__icn"><div class="pswp__preloader__cut"><div class="pswp__preloader__donut"></div></div></div></div></div><div class="pswp__share-modal pswp__share-modal--hidden pswp__single-tap"><div class="pswp__share-tooltip"></div></div><button class="pswp__button pswp__button--arrow--left" title="Previous (arrow left)"></button><button class="pswp__button pswp__button--arrow--right" title="Next (arrow right)"></button><div class="pswp__caption"><div class="pswp__caption__center"></div></div></div></div></div>';

            // 避免多次实例化后 生成多个container
            if ($('body').children('.pswp').length === 0) {
                $('body').append(this.psDom);
            } else {
                $('body').find('.pswp').remove().append(this.psDom);
            }
        },
        showPhotoWall: function (photoWalls, index) {
            var pswpElement = document.querySelectorAll('.pswp')[0],
                items = [],
                t = this;

            if (photoWalls.length > 0) {
                photoWalls.forEach(function (value, key) {
                    items.push($.extend({w: 500, h: 500, loadLock: true}, value));
                });
            }

            var options = {
                index: index,
                history: false,  // 不改变hash
                focus: false,
                shareEl: false,  // 分享
                fullscreenEl: false,  // 全屏
                showHideOpacity: true,  // 展示隐藏效果渐隐

                showAnimationDuration: 300,
                hideAnimationDuration: 300,

                // 展示隐藏效果 （展示的效果有bug，暂未发现原因，待完善）
                getThumbBoundsFn: function (index) {
                    if (items[index].el) {
                        var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                            pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                            rect = thumbnail.getBoundingClientRect();

                        return {x: rect.left, y: rect.top + pageYScroll, w: rect.width};
                    } else {
                        return {x: 0, y: 0, w: 0};
                    }

                }
            };

            var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, items, options);

            gallery.listen("gettingData", function (index, slide) {
                if (slide.loadLock) {
                    setTimeout(function () {
                        t.getSlideDimensions(gallery, slide);
                    }, 300);
                }
            });

            gallery.listen("imageLoadComplete", function (index, slide) {
                if (slide.loadLock) {
                    t.getSlideDimensions(gallery, slide);
                }
            });

            gallery.init();
        },
        // 图片宽高自适应
        getSlideDimensions: function (gallery, slide) {
            // 阻止多次触发
            if (!slide.loadLock) return;

            var img = new Image();

            $(img).on("error", function (evt) {
                slide.loadLock = false;
            });

            $(img).on("load", function (evt) {
                slide.loadLock = false;

                slide.w = img.naturalWidth;
                slide.h = img.naturalHeight;

                gallery.invalidateCurrItems();
                gallery.updateSize(true);
            });

            img.src = slide.src;
        }
    };

    (function () {
        if (!photoSwipeInstance) {
            photoSwipeInstance = new photoSwipe();
        }
    })();

    return photoSwipeInstance;
});
